﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using HRM.BusinessLogic;
using HeaderInfo = HRM.BusinessLogic.BhHeaderInfo;
using RateInfo = HRM.BusinessLogic.RateInfo;
namespace HRM
{
    public partial class frmFundList : FormBase
    {
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        int SalaryFundID;
        int _IsApproved = 0;
        bool _loadedData = true;
        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        ParameterClient wcfParameter;
        SalaryFundClient _wcfSalaryFund;
        SalaryFundInfo _SalaryFundInfo;
        MainServiceClient wcfMainService;
        SalaryClient _wcfSalary;
        DetailClient _wclDetail;
        string _date;
        string _Type = InsuranceType.HS;
        decimal _SocialInc;
        decimal _MedicalInc; RoleRightInfo listRole;
        DateTime _dateCal = DateTime.MinValue;
        int approvedStatus = 0;


        public frmFundList(string Type)
        {
            InitializeComponent();
            this.KeyPreview = true;
            this.TabText = this.TabText + (Type == "HS" ? " - Hệ số" : " - Mức lương");
            //LoadLanguage();
            _wcfSalaryFund = Service.SalaryFund();
            listRole = UIParamater.Quyen_DoiChieuQuyBHXH;
            _wclDetail = Service.Detail();
            BuildVoucherGrid();
            UISetting.LoadMonths(ref cboMonth);
            UISetting.LoadYears(ref cboYear);
            _Type = Type;
            LoadRole();
            LoadData();
            _loadedData = true;
            toolStripLabel2.Visible = false;
            cboMonth.Visible = false;
            btnDel.Enabled = Program.isChuyenQuan;
        }

        protected override void Init_Control()
        {
            base.Init_Control();
        }

        public override void Show_Form()
        {
            this.Show();
        }

        void LoadRole()
        {
            if (!listRole.Create)
                btnOpenBook.Enabled = false;
            else
                btnOpenBook.Enabled = true;
            if (!listRole.Update)
            {
                btnUpdate.Enabled = false;
                btnEdit.Enabled = false;
            }
            else
            {
                btnUpdate.Enabled = true;
                btnEdit.Enabled = true;
            }
            //if (!listRole.Delete)
            //    btnDel.Enabled = false;
            //else
            //    btnDel.Enabled = true;
            if (!listRole.Print)
                btnPrint.Enabled = false;
            else
                btnPrint.Enabled = true;
        }
        void LoadLanguage()
        {
            if (this.Tag != null)
                this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }
        private void BuildVoucherGrid()
        {
            UISetting.AddColumn(ref dgvList, "SalaryFund_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_Month", "Tháng/Năm", "C", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_Quater", "Quý", "C", 90, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHYTEmployee", "LĐ BHYT", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHYTAmount", "Quỹ BHYT", "R", 120, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHYTThua", "Thừa", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHYTThieu", "Thiếu", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHTNEmployee", "LĐ BHTN", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHTNAmount", "Quỹ BHTN", "R", 120, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHTNThua", "Thừa", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHTNThieu", "Thiếu", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHXHEmployee", "LĐ BHXH", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHXHAmount", "Quỹ BHXH", "R", 120, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHXHThua", "Thừa", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_BHXHThieu", "Thiếu", "R", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_IsApproved_Text", "Đóng sổ", "L", 100, true, true);
            UISetting.AddColumn(ref dgvList, "SalaryFund_IsApproved", "Đóng sổ", "L", 100, false, true);
        }
        private void LoadData()
        {
            int temptYear;
            if (Int32.TryParse(cboYear.Text, out temptYear))
                _year = temptYear;
            DataSet _ds = _wcfSalaryFund.SalaryFund_GetList(out itemCount, currPage, pageSize, _year, Program.strBranchBHXH);
            PageIndex();
            dgvList.Rows.Clear();
            int n = _ds.Tables[0].Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList.Rows.Insert(i, 1);
                dgvList.Rows[i].Cells["SalaryFund_ID"].Value = _ds.Tables[0].Rows[i]["SalaryFund_ID"].ToString();
                dgvList.Rows[i].Cells["SalaryFund_Month"].Value = Convert.ToDateTime(_ds.Tables[0].Rows[i]["SalaryFund_Month"]).ToString("MM/yyy");
                dgvList.Rows[i].Cells["SalaryFund_Quater"].Value = _ds.Tables[0].Rows[i]["SalaryFund_Quater"].ToString();
                dgvList.Rows[i].Cells["SalaryFund_BHYTAmount"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHYTAmount"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHYTEmployee"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHYTEmployee"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHYTThua"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHYTThua"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHYTThieu"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHYTThieu"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHTNAmount"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHTNAmount"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHTNEmployee"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHTNEmployee"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHTNThua"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHTNThua"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHTNThieu"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHTNThieu"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHXHAmount"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHXHAmount"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHXHEmployee"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHXHEmployee"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHXHThua"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHXHThua"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_BHXHThieu"].Value = Convert.ToDecimal(_ds.Tables[0].Rows[i]["SalaryFund_BHXHThieu"]).ToString("#,##0");
                dgvList.Rows[i].Cells["SalaryFund_IsApproved_Text"].Value = Convert.ToInt32(_ds.Tables[0].Rows[i]["SalaryFund_IsApproved"]) == 1 ? "Mở sổ" : "Đóng sổ";
                dgvList.Rows[i].Cells["SalaryFund_IsApproved"].Value = _ds.Tables[0].Rows[i]["SalaryFund_IsApproved"];
            }
            if (dgvList.Rows.Count > 0)
            {
                dgvList.Rows[0].Selected = true;
                EnableButton();
            }
        }

        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void btnOpenBook_Click(object sender, EventArgs e)
        {
            //Tao ban ghi moi cho thang ke tiep:
            if (!listRole.Create)
            {
                MessageBox.Show("Bạn không có quyền kết chuyển sang tháng sau", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DateTime _ThisMonth = DateTime.MinValue;
            DataTable dtdate = _wcfSalaryFund.SalaryFund_GetDate(Program.strBranchBHXH).Tables[0];
            if (dtdate.Rows.Count > 0)
                _ThisMonth = Convert.ToDateTime(dtdate.Rows[0]["SalaryFund_Month"]);
            else
                _ThisMonth = DateTime.Now.Date;

            DataTable dt = _wcfSalaryFund.SalaryFund_GetData(_ThisMonth.Month, _ThisMonth.Year, Program.strBranchBHXH).Tables[0];
            if (dt.Rows.Count > 0)
            {
                _SalaryFundInfo = new SalaryFundInfo();
                _SalaryFundInfo.BranchCode = Program.strBranchBHXH;
                _SalaryFundInfo.Month = _ThisMonth.AddMonths(1);
                _month = _SalaryFundInfo.Month.Month;
                _year = _SalaryFundInfo.Month.Year;
                _SalaryFundInfo.IsApproved = 1;
                if (_month < 4)
                    _SalaryFundInfo.Quater = "1" + "/" + _year.ToString();
                else if (_month < 7)
                    _SalaryFundInfo.Quater = "2" + "/" + _year.ToString();
                else if (_month < 10)
                    _SalaryFundInfo.Quater = "3" + "/" + _year.ToString();
                else if (_month < 13)
                    _SalaryFundInfo.Quater = "4" + "/" + _year.ToString();

                //BHYT:
                _SalaryFundInfo.BHYT_Employee = Convert.ToInt32(dt.Rows[0]["SalaryFund_BHYTEmployee"]);
                _SalaryFundInfo.BHYT_Amount = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHYTAmount"]);
                _SalaryFundInfo.BHYT_HaveToPaid = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHYTHaveToPaid"]);
                _SalaryFundInfo.BHYT_Increase = 0;
                _SalaryFundInfo.BHYT_Decrease = 0;
                _SalaryFundInfo.BHYT_PaidAmount = 0;
                _SalaryFundInfo.BHYT_Sum = 0;
                _SalaryFundInfo.BHYT_Thieu = 0;
                _SalaryFundInfo.BHYT_Thua = 0;
                _SalaryFundInfo.BHYT_KyTruocThua = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHYTThua"]);
                _SalaryFundInfo.BHYT_KyTruocThieu = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHYTThieu"]);

                //BHTN:
                _SalaryFundInfo.BHTN_Employee = Convert.ToInt32(dt.Rows[0]["SalaryFund_BHTNEmployee"]);
                _SalaryFundInfo.BHTN_Amount = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHTNAmount"]);
                _SalaryFundInfo.BHTN_HaveToPaid = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHTNHaveToPaid"]);
                _SalaryFundInfo.BHTN_Increase = 0;
                _SalaryFundInfo.BHTN_Decrease = 0;
                _SalaryFundInfo.BHTN_PaidAmount = 0;
                _SalaryFundInfo.BHTN_Sum = 0;
                _SalaryFundInfo.BHTN_Thieu = 0;
                _SalaryFundInfo.BHTN_Thua = 0;
                _SalaryFundInfo.BHTN_KyTruocThua = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHTNThua"]);
                _SalaryFundInfo.BHTN_KyTruocThieu = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHTNThieu"]);

                //BHXH:
                _SalaryFundInfo.BHXH_Employee = Convert.ToInt32(dt.Rows[0]["SalaryFund_BHXHEmployee"]);
                _SalaryFundInfo.BHXH_Amount = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHXHAmount"]);
                _SalaryFundInfo.BHXH_HaveToPaid = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHXHHaveToPaid"]);
                _SalaryFundInfo.BHXH_Increase = 0;
                _SalaryFundInfo.BHXH_Decrease = 0;
                _SalaryFundInfo.BHXH_PaidAmount = 0;
                _SalaryFundInfo.BHXH_Sum = 0;
                _SalaryFundInfo.BHXH_Thieu = 0;
                _SalaryFundInfo.BHXH_Thua = 0;
                _SalaryFundInfo.BHXH_KyTruocThua = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHXHThua"]);
                _SalaryFundInfo.BHXH_KyTruocThieu = Convert.ToDecimal(dt.Rows[0]["SalaryFund_BHXHThieu"]);

                _SalaryFundInfo.PhatKyTruoc = Convert.ToDecimal(dt.Rows[0]["SalaryFund_ChamNop_KySau"]);
                _SalaryFundInfo.PhatKyNay = 0;
                _SalaryFundInfo.PhatDaNop = 0;
                _SalaryFundInfo.PhatKySau = 0;

                if (_wcfSalaryFund.SalaryFund_CheckExist(0, Program.strBranchBHXH, _SalaryFundInfo.Quater, _SalaryFundInfo.Month) <= 0)
                {
                    if (_wcfSalaryFund.SalaryFund_Insert(_SalaryFundInfo) > 0)
                        LoadData();
                }
            }
            else
            {
                //InsertHeader();
                _SalaryFundInfo = new SalaryFundInfo();
                _SalaryFundInfo.ID = 0;
                _SalaryFundInfo.BranchCode = Program.strBranchBHXH;
                _SalaryFundInfo.Month = DateTime.Now.Date;
                _month = DateTime.Now.Date.Month;
                _SalaryFundInfo.IsApproved = 1;
                if (_month < 4)
                    _SalaryFundInfo.Quater = "1" + "/" + cboYear.Text;
                else if (_month < 7)
                    _SalaryFundInfo.Quater = "2" + "/" + cboYear.Text;
                else if (_month < 10)
                    _SalaryFundInfo.Quater = "3" + "/" + cboYear.Text;
                else if (_month < 13)
                    _SalaryFundInfo.Quater = "4" + "/" + cboYear.Text;
                if (_wcfSalaryFund.SalaryFund_CheckExist(0, Program.strBranchCode, _SalaryFundInfo.Quater, DateTime.Now.Date) <= 0)
                    _wcfSalaryFund.SalaryFund_Insert(_SalaryFundInfo);
                LoadData();

            }
        }
        void InsertHeader()
        {
            //HeaderClient _wcfHeader = Service.Header();
            HeaderInfo _HeaderInfo;
            RateClient _wcfRate = Service.Rate();
            RateInfo _RateInfo = new RateInfo();
            BranchClient _wcfBranch = Service.Branch();
            _RateInfo = Rate_Controller.Instance().Rate_GetInfoByDate(DateTime.Now.Date);
            _HeaderInfo = new HeaderInfo();
            _HeaderInfo.Document_Id = 0;
            _HeaderInfo.Document_Branchcode = Program.strBranchCode;
            _HeaderInfo.Document_Date = DateTime.Now.Date;
            _HeaderInfo.Document_Period = 1;
            _HeaderInfo.Document_Month = DateTime.Now.Date.Month;
            _HeaderInfo.Document_Year = DateTime.Now.Date.Year;
            _HeaderInfo.Document_Social = _RateInfo.Rate_Social;
            _HeaderInfo.Document_Medical = _RateInfo.Rate_Medical;
            _HeaderInfo.Document_Unemployed = _RateInfo.Rate_Unemployed;
            _HeaderInfo.Document_Basicsalary = _wcfBranch.Branch_GetInfo(Program.intBranchID).MinBasicSalary;
            _HeaderInfo.Document_Type = _Type;
            _HeaderInfo.Document_Isinitial = false;
            if (!BhHeader_Controller.Instance().Header_CheckExist(0, Program.strBranchCode, DateTime.Now.Date, _HeaderInfo.Document_Month, _HeaderInfo.Document_Year, _HeaderInfo.Document_Period,_HeaderInfo.Document_Type))
                BhHeader_Controller.Instance().Header_Insert(_HeaderInfo);
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (!listRole.Delete)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                string _App = "";
                SalaryFundID = Convert.ToInt32(dgvList.SelectedRows[0].Cells["SalaryFund_ID"].Value);
                _App = dgvList.SelectedRows[0].Cells["SalaryFund_IsApproved"].Value.ToString();
                int _IDval = 0;
                DataTable dtDate = _wcfSalaryFund.SalaryFund_GetDate(Program.strBranchCode).Tables[0];
                if (dtDate.Rows.Count > 0)
                    _IDval = Convert.ToInt32(dtDate.Rows[0]["SalaryFund_ID"]);
                if (SalaryFundID != _IDval)
                {
                    MessageBox.Show("Phải xóa tháng mới nhất trước!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                //if (_App != "Đóng sổ")
                //{
                if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (_wcfSalaryFund.SalaryFund_Delete(SalaryFundID))
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        LoadData();
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                //}
                //else
                //    MessageBox.Show("Tháng này đã đóng sổ, không xóa được", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (listRole.Update || listRole.View)
                {
                    SalaryFundID = Convert.ToInt32(dgvList.SelectedRows[0].Cells["SalaryFund_ID"].Value);
                    Form f = new frmSalaryFundInfo(SalaryFundID, listRole);
                    ((frmSalaryFundInfo)f).afterCloseBook += new frmSalaryFundInfo.AfterCloseBook(frmSalaryFundInfo_AfterCloseBook);
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        LoadData();
                    }
                }
                else
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void frmSalaryFundInfo_AfterCloseBook()
        {            
            btnCalculate_Click(null, null);
            //LoadData();
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage > 0 && currPage != totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage != 0)
                currPage--;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage != 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //btnEdit_Click(null, null);
            
                btnUpdate_Click(null, null);
        }

        private void frmFundList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    btnUpdate_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
                case Keys.F4:
                    btnOpenBook_Click(null, null);
                    break;
                case Keys.F5:
                    btnCalculate_Click(null, null);
                    break;
                case Keys.Delete:
                    if (e.Control)
                        btnDel_Click(null, null);
                    break;
            }
        }

        private void btnCloseBook_Click(object sender, EventArgs e)
        {
            if (!listRole.Update)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyencapnhat"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (dgvList.SelectedRows.Count > 0)
            {
                if (MessageBox.Show("Bạn có chắc chắn đóng sổ tháng này không!", UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    SalaryFundID = Convert.ToInt32(dgvList.SelectedRows[0].Cells["SalaryFund_ID"].Value);
                    string sql = "Update HRM_SalaryFund SET SalaryFund_IsApproved = 2 WHERE SalaryFund_ID = " + SalaryFundID.ToString();
                    wcfMainService = Service.MainService();
                    wcfMainService.ExecuteQuery(sql);
                    Program.taskbarNotifier.Show(UIParamater.TitleProject, "Đóng sổ thành công!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    LoadData();
                }
            }
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (_loadedData)
            //{
            //    _month = Convert.ToInt32(cboMonth.Text);
            //    LoadData();
            //}
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                currPage = 0;
                LoadData();
            }
        }

        private void dgvList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            EnableButton();
        }

        void EnableButton()
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                DateTime _CompareDate = DateTime.MinValue;
                _CompareDate = Convert.ToDateTime(_wcfSalaryFund.SalaryFund_GetDate(Program.strBranchBHXH).Tables[0].Rows[0]["SalaryFund_Month"]);
                approvedStatus = Globals.Object_GetValue<int>(dgvList.SelectedRows[0].Cells["SalaryFund_IsApproved"].Value);
                _dateCal = Convert.ToDateTime(dgvList.SelectedRows[0].Cells["SalaryFund_Month"].Value);
                if (approvedStatus == (int)ApprovedStatus.DongSo && _CompareDate == _dateCal)
                {
                    btnOpenBook.Enabled = true;
                    btnUpdate.Text = "Xem phát sinh";
                    //btnEdit.Enabled = false;
                    btnCalculate.Enabled = false;
                }
                else if (approvedStatus == (int)ApprovedStatus.MoSo && _CompareDate.Month == _dateCal.Month && _CompareDate.Year == _dateCal.Year)
                //else if (_App == "Mở sổ" && _CompareDate == _dateCal)
                {
                    btnUpdate.Text = "Cập nhật phát sinh";
                    btnCalculate.Enabled = true;
                    btnOpenBook.Enabled = false;
                    btnEdit.Enabled = true;
                }
                else
                {
                    //btnUpdate.Enabled = true;
                    //btnEdit.Enabled = false;
                    btnUpdate.Text = "Xem phát sinh";
                    btnCalculate.Enabled = false;
                    btnOpenBook.Enabled = false;
                }
                //btnDel.Enabled = listRole.Delete;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            //Nếu form xem chi tiết đang mở thì ko mở nữa
            FormCollection fc = Application.OpenForms;
            frmInsurance frmTmp = new frmInsurance();
            bool IsOpen = false;
            foreach (Form frm in fc){
                if (frm.GetType().Equals(frmTmp.GetType())){
                    IsOpen = true;
                    frm.Focus();
                    break;
                }
            }
            if (IsOpen) return;

            //Cập nhật phát sinh:
            HeaderClient _wcfHeader = Service.Header();
            HeaderInfo _HeaderInfo = new HeaderInfo();
            int _DocumentID = 0;
            int _Approved = 0;
            if (dgvList.SelectedRows.Count > 0)
            {
                //InsertHeader();
                _dateCal = UISetting.GetDate(dgvList.SelectedRows[0].Cells["SalaryFund_Month"].Value.ToString());
                _month = _dateCal.Month;
                _year = _dateCal.Year;
                approvedStatus = Globals.Object_GetValue<int>(dgvList.SelectedRows[0].Cells["SalaryFund_IsApproved"].Value);

                _HeaderInfo = BhHeader_Controller.Instance().Header_GetMaxBymonth(_month, _year, Program.strBranchBHXH, _Type);
                //_HeaderInfo = _wcfHeader.Header_GetMaxBymonth(_month, _year, Program.strBranchBHXH, _Type);
                if (_HeaderInfo != null)
                    _DocumentID = Convert.ToInt32(_HeaderInfo.Document_Id);
                else
                    _DocumentID = 0;
                if (approvedStatus == (int)ApprovedStatus.DongSo)
                    _Approved = 2;
                else
                    _Approved = 1;

                frmInsurance f = new frmInsurance(_DocumentID, listRole, _dateCal, _Type,  _Approved);
                //f.Show(this.dockPanelHRM);
                f.ShowDialog();
            }
        }

        //Sau khi đóng frm phát sinh,tự động gọi làm mới số liệu nếu 
        void frmInsurance_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Nếu kỳ đang mở là kỳ cuối,
            if( ((frmInsurance)sender)._Approved == 1)
                btnCalculate_Click(null, null);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {

            if (dgvList.SelectedRows.Count > 0)
            {
                _dateCal = UISetting.GetDate(dgvList.SelectedRows[0].Cells["SalaryFund_Month"].Value.ToString());
                _month = _dateCal.Month;
                _year = _dateCal.Year;
                if (listRole.View)
                {
                    frmPreviewReport f = new frmPreviewReport("BHXHMau08", new string[] { "Mẫu 08", _month.ToString(), _year.ToString() });
                    f.Show(this);
                }
                else
                    MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
                MessageBox.Show("Hãy chọn 1 tháng để xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            //Update ban ghi:
            //Tinh quy luong cua cong ty:

            DataTable dtLast = new DataTable();
            DataTable dtNow = new DataTable();
            DataTable dt = new DataTable();
            DataTable dtResult = new DataTable();
            if (dgvList.SelectedRows.Count > 0)
            {
                _dateCal = UISetting.GetDate(dgvList.SelectedRows[0].Cells["SalaryFund_Month"].Value.ToString());
                _month = _dateCal.Month;
                _year = _dateCal.Year;

                if (_month > 0)
                {
                    //Ky truoc:
                    dtLast = _wcfSalaryFund.SalaryFund_GetLastData(_month, _year, Program.strBranchBHXH).Tables[0];
                    //Tang giam:
                    dt = _wclDetail.Detail_TongHopMau03(0, _month, _year, Program.strBranchBHXH).Tables[0];
                    //Kỳ này:
                    dtNow = _wcfSalaryFund.SalaryFund_GetData(_month, _year, Program.strBranchBHXH).Tables[0];

                    dtResult = _wclDetail.Detail_Mau03CuoiKy(0, _month, _year, Program.strBranchBHXH).Tables[0];
                }
                //Ky nay:
                _SalaryFundInfo = new SalaryFundInfo();
                _SalaryFundInfo.ID = UISetting.GetIntNo(dgvList.SelectedRows[0].Cells["SalaryFund_ID"].Value.ToString());
                _SalaryFundInfo.BranchCode = Program.strBranchBHXH;
                _SalaryFundInfo.Month = _dateCal;
                _SalaryFundInfo.IsApproved = 1;
                if (_month < 4)
                    _SalaryFundInfo.Quater = "1" + "/" + cboYear.Text;
                else if (_month < 7)
                    _SalaryFundInfo.Quater = "2" + "/" + cboYear.Text;
                else if (_month < 10)
                    _SalaryFundInfo.Quater = "3" + "/" + cboYear.Text;
                else if (_month < 13)
                    _SalaryFundInfo.Quater = "4" + "/" + cboYear.Text;

                //BHYT:
                _SalaryFundInfo.BHYT_Employee = Convert.ToInt32(dtResult.Rows[0]["BHYT_LDKyNay"]);
                _SalaryFundInfo.BHYT_Amount = Convert.ToDecimal(dtResult.Rows[0]["BHYT_QuyLuongKyNay"]);
                _SalaryFundInfo.BHYT_HaveToPaid = Convert.ToDecimal(dtResult.Rows[0]["BHYT_QuyLuongKyNay_PhaiDong"]);
                _SalaryFundInfo.BHYT_Increase = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHYT_DCTang"].ToString());
                _SalaryFundInfo.BHYT_Decrease = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHYT_DCGiam"].ToString());

                if (dtLast.Rows.Count > 0)
                {
                    _SalaryFundInfo.BHYT_KyTruocThieu = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHYTThieu"]);
                    _SalaryFundInfo.BHYT_KyTruocThua = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHYTThua"]);
                }
                else
                {
                    _SalaryFundInfo.BHYT_KyTruocThieu = 0;
                    _SalaryFundInfo.BHYT_KyTruocThua = 0;
                }
                _SalaryFundInfo.BHYT_Sum = _SalaryFundInfo.BHYT_HaveToPaid + _SalaryFundInfo.BHYT_Increase - _SalaryFundInfo.BHYT_Decrease + _SalaryFundInfo.BHYT_KyTruocThieu - _SalaryFundInfo.BHYT_KyTruocThua;
                _SalaryFundInfo.BHYT_PaidAmount = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_BHYTPaidAmount"]);
                if (_SalaryFundInfo.BHYT_PaidAmount >= _SalaryFundInfo.BHYT_Sum)
                    _SalaryFundInfo.BHYT_Thua = _SalaryFundInfo.BHYT_PaidAmount - _SalaryFundInfo.BHYT_Sum;
                else
                    _SalaryFundInfo.BHYT_Thieu = _SalaryFundInfo.BHYT_Sum - _SalaryFundInfo.BHYT_PaidAmount;

                //BHTN:
                _SalaryFundInfo.BHTN_Employee = Convert.ToInt32(dtResult.Rows[0]["BHTN_LDKyNay"]);
                _SalaryFundInfo.BHTN_Amount = Convert.ToDecimal(dtResult.Rows[0]["BHTN_QuyLuongKyNay"]);
                _SalaryFundInfo.BHTN_HaveToPaid = Convert.ToDecimal(dtResult.Rows[0]["BHTN_QuyLuongKyNay_PhaiDong"]);
                _SalaryFundInfo.BHTN_Increase = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHTN_DCTang"].ToString());
                _SalaryFundInfo.BHTN_Decrease = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHTN_DCGiam"].ToString());
                if (dtLast.Rows.Count > 0)
                {
                    _SalaryFundInfo.BHTN_KyTruocThieu = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHTNThieu"]);
                    _SalaryFundInfo.BHTN_KyTruocThua = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHTNThua"]);
                }
                else
                {
                    _SalaryFundInfo.BHTN_KyTruocThieu = 0;
                    _SalaryFundInfo.BHTN_KyTruocThua = 0;
                }
                _SalaryFundInfo.BHTN_Sum = _SalaryFundInfo.BHTN_HaveToPaid + _SalaryFundInfo.BHTN_Increase - _SalaryFundInfo.BHTN_Decrease + _SalaryFundInfo.BHTN_KyTruocThieu - _SalaryFundInfo.BHTN_KyTruocThua;
                _SalaryFundInfo.BHTN_PaidAmount = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_BHTNPaidAmount"]);
                if (_SalaryFundInfo.BHTN_PaidAmount >= _SalaryFundInfo.BHTN_Sum)
                    _SalaryFundInfo.BHTN_Thua = _SalaryFundInfo.BHTN_PaidAmount - _SalaryFundInfo.BHTN_Sum;
                else
                    _SalaryFundInfo.BHTN_Thieu = _SalaryFundInfo.BHTN_Sum - _SalaryFundInfo.BHTN_PaidAmount;

                //BHXH:
                _SalaryFundInfo.BHXH_Employee = Convert.ToInt32(dtResult.Rows[0]["BHXH_LDKyNay"]);
                _SalaryFundInfo.BHXH_Amount = Convert.ToDecimal(dtResult.Rows[0]["BHXH_QuyLuongKyNay"]);
                _SalaryFundInfo.BHXH_HaveToPaid = Convert.ToDecimal(dtResult.Rows[0]["BHXH_QuyLuongKyNay_PhaiDong"]);
                _SalaryFundInfo.BHXH_Increase = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHXH_DCTang"].ToString());
                _SalaryFundInfo.BHXH_Decrease = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHXH_DCGiam"].ToString());
                if (dtLast.Rows.Count > 0)
                {
                    _SalaryFundInfo.BHXH_KyTruocThieu = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHXHThieu"]);
                    _SalaryFundInfo.BHXH_KyTruocThua = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHXHThua"]);
                    _SalaryFundInfo.PhatKyTruoc = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_ChamNop_KySau"]);
                }
                else
                {
                    _SalaryFundInfo.BHXH_KyTruocThieu = 0;
                    _SalaryFundInfo.BHXH_KyTruocThua = 0;
                    _SalaryFundInfo.PhatKyTruoc = 0;
                }
                _SalaryFundInfo.BHXH_Sum = _SalaryFundInfo.BHXH_HaveToPaid + _SalaryFundInfo.BHXH_Increase - _SalaryFundInfo.BHXH_Decrease + _SalaryFundInfo.BHXH_KyTruocThieu - _SalaryFundInfo.BHXH_KyTruocThua;
                _SalaryFundInfo.BHXH_PaidAmount = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_BHXHPaidAmount"]);
                if (_SalaryFundInfo.BHXH_PaidAmount >= _SalaryFundInfo.BHXH_Sum)
                    _SalaryFundInfo.BHXH_Thua = _SalaryFundInfo.BHXH_PaidAmount - _SalaryFundInfo.BHXH_Sum;
                else
                    _SalaryFundInfo.BHXH_Thieu = _SalaryFundInfo.BHXH_Sum - _SalaryFundInfo.BHXH_PaidAmount;


                _SalaryFundInfo.PhatKyNay = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_ChamNop_KyNay"]);
                _SalaryFundInfo.PhatDaNop = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_ChamNop_DaDong"]);
                _SalaryFundInfo.PhatKySau = (_SalaryFundInfo.PhatKyTruoc + _SalaryFundInfo.PhatKyNay) - _SalaryFundInfo.PhatDaNop;

                #region Rem All:
                //BHYT:
                //_SalaryFundInfo.BHYT_Employee = Convert.ToInt32(dtLast.Rows[0]["SalaryFund_BHYTEmployee"]) + Convert.ToInt32(dt.Rows[0]["SoNV_BHYT_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoNV_BHYT_Giam"]);
                //_SalaryFundInfo.BHYT_Amount = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHYTAmount"]) + Convert.ToInt32(dt.Rows[0]["SoTien_BHYT_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoTien_BHYT_Giam"]);
                //_SalaryFundInfo.BHYT_HaveToPaid = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHYTHaveToPaid"]) + Convert.ToInt32(dt.Rows[0]["SoTien_BHYT_PhaiNop_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoTien_BHYT_PhaiNop_Giam"]);
                //_SalaryFundInfo.BHYT_Increase = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHYT_DCTang"].ToString());
                //_SalaryFundInfo.BHYT_Decrease = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHYT_DCGiam"].ToString());
                //_SalaryFundInfo.BHYT_KyTruocThieu = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHYTThieu"]);
                //_SalaryFundInfo.BHYT_KyTruocThua = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHYTThua"]);
                //_SalaryFundInfo.BHYT_Sum = _SalaryFundInfo.BHYT_HaveToPaid + _SalaryFundInfo.BHYT_Increase - _SalaryFundInfo.BHYT_Decrease + _SalaryFundInfo.BHYT_KyTruocThieu - _SalaryFundInfo.BHYT_KyTruocThua;
                //_SalaryFundInfo.BHYT_PaidAmount = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_BHYTPaidAmount"]);
                //if (_SalaryFundInfo.BHYT_PaidAmount >= _SalaryFundInfo.BHYT_Sum)
                //    _SalaryFundInfo.BHYT_Thua = _SalaryFundInfo.BHYT_PaidAmount - _SalaryFundInfo.BHYT_Sum;
                //else
                //    _SalaryFundInfo.BHYT_Thieu = _SalaryFundInfo.BHYT_Sum - _SalaryFundInfo.BHYT_PaidAmount;

                ////BHTN:
                //_SalaryFundInfo.BHTN_Employee = Convert.ToInt32(dtLast.Rows[0]["SalaryFund_BHTNEmployee"]) + Convert.ToInt32(dt.Rows[0]["SoNV_BHTN_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoNV_BHTN_Giam"]);
                //_SalaryFundInfo.BHTN_Amount = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHTNAmount"]) + Convert.ToInt32(dt.Rows[0]["SoTien_BHTN_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoTien_BHTN_Giam"]);
                //_SalaryFundInfo.BHTN_HaveToPaid = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHTNHaveToPaid"]) + Convert.ToInt32(dt.Rows[0]["SoTien_BHTN_PhaiNop_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoTien_BHTN_PhaiNop_Giam"]);
                //_SalaryFundInfo.BHTN_Increase = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHTN_DCTang"].ToString());
                //_SalaryFundInfo.BHTN_Decrease = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHTN_DCGiam"].ToString());
                //_SalaryFundInfo.BHTN_KyTruocThieu = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHTNThieu"]);
                //_SalaryFundInfo.BHTN_KyTruocThua = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHTNThua"]);
                //_SalaryFundInfo.BHTN_Sum = _SalaryFundInfo.BHTN_HaveToPaid + _SalaryFundInfo.BHTN_Increase - _SalaryFundInfo.BHTN_Decrease + _SalaryFundInfo.BHTN_KyTruocThieu - _SalaryFundInfo.BHTN_KyTruocThua;
                //_SalaryFundInfo.BHTN_PaidAmount = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_BHTNPaidAmount"]);
                //if (_SalaryFundInfo.BHTN_PaidAmount >= _SalaryFundInfo.BHTN_Sum)
                //    _SalaryFundInfo.BHTN_Thua = _SalaryFundInfo.BHTN_PaidAmount - _SalaryFundInfo.BHTN_Sum;
                //else
                //    _SalaryFundInfo.BHTN_Thieu = _SalaryFundInfo.BHTN_Sum - _SalaryFundInfo.BHTN_PaidAmount;

                ////BHXH:
                //_SalaryFundInfo.BHXH_Employee = Convert.ToInt32(dtLast.Rows[0]["SalaryFund_BHXHEmployee"]) + Convert.ToInt32(dt.Rows[0]["SoNV_BHXH_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoNV_BHXH_Giam"]);
                //_SalaryFundInfo.BHXH_Amount = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHXHAmount"]) + Convert.ToInt32(dt.Rows[0]["SoTien_BHXH_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoTien_BHXH_Giam"]);
                //_SalaryFundInfo.BHXH_HaveToPaid = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHXHHaveToPaid"]) + Convert.ToInt32(dt.Rows[0]["SoTien_BHXH_PhaiNop_Tang"]) - Convert.ToInt32(dt.Rows[0]["SoTien_BHXH_PhaiNop_Giam"]);
                //_SalaryFundInfo.BHXH_Increase = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHXH_DCTang"].ToString());
                //_SalaryFundInfo.BHXH_Decrease = UISetting.GetDecimalNo(dt.Rows[0]["Sotien_BHXH_DCGiam"].ToString());
                //_SalaryFundInfo.BHXH_KyTruocThieu = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHXHThieu"]);
                //_SalaryFundInfo.BHXH_KyTruocThua = Convert.ToDecimal(dtLast.Rows[0]["SalaryFund_BHXHThua"]);
                //_SalaryFundInfo.BHXH_Sum = _SalaryFundInfo.BHXH_HaveToPaid + _SalaryFundInfo.BHXH_Increase - _SalaryFundInfo.BHXH_Decrease + _SalaryFundInfo.BHXH_KyTruocThieu - _SalaryFundInfo.BHXH_KyTruocThua;
                //_SalaryFundInfo.BHXH_PaidAmount = Convert.ToDecimal(dtNow.Rows[0]["SalaryFund_BHXHPaidAmount"]);
                //if (_SalaryFundInfo.BHXH_PaidAmount >= _SalaryFundInfo.BHXH_Sum)
                //    _SalaryFundInfo.BHXH_Thua = _SalaryFundInfo.BHXH_PaidAmount - _SalaryFundInfo.BHXH_Sum;
                //else
                //    _SalaryFundInfo.BHXH_Thieu = _SalaryFundInfo.BHXH_Sum - _SalaryFundInfo.BHXH_PaidAmount;
                #endregion

                if (_wcfSalaryFund.SalaryFund_Update(_SalaryFundInfo))
                {
                    Program.taskbarNotifier.Show(UIParamater.TitleProject, "Cập nhật số liệu \nthành công!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    LoadData();
                }
            }
        }
    }
}

